#-------------------------------------------------------------------------------
# Name:        module1
# Purpose:
#
# Author:      patrick
#
# Created:     16/05/2012
# Copyright:   (c) patrick 2012
# Licence:     <your licence>
#-------------------------------------------------------------------------------
#!/usr/bin/env python


from moddt8837 import *
import pylab as plt
import time
import numpy as np
import scipy as sc
import struct
import time

def save2disk(h,ideb,ifin,sizeblock):
    """ procedure de sauvegarded sur disque """
    """ entre un index de debut et un index de fin  """
    print "----------------------------------"
    print ideb,ifin
    nbblock=int((ifin-ideb)/sizeblock)
    reste = (ifin - ideb+1)-nbblock*sizeblock
    buf=[]
    for k in range(nbblock):
        i0=sizeblock*k+ideb
        i1=i0+sizeblock-1
        mess=":AD:FETCH? "+str(i0)+","+str(sizeblock)
##        print mess
        err1=h.write (mess)
        data=h.read_raw()
        sizeHeader,sizeBuffer,header,buf1 =  readHeader(data)
        buf=np.concatenate(( buf,buf1), axis=0)
    i0=i1+1
    i1=i0+reste-1
    mess=":AD:FETCH? "+str(i0)+","+str(reste)
##    print mess
    err1=h.write (mess)
    data=h.read_raw()
    sizeHeader,sizeBuffer,header,buf1 =  readHeader(data)
    buf=np.concatenate(( buf,buf1), axis=0)
    return buf

def GetAdBufferStatus(h):
    err = h.write(":AD:STAT?;:AD:STAT:SCAN?")
    if err is not None:
        print 'Erreur AD getAdBufferStatus...'
    s = h.read()
    s=s.split(";")
    ADstatus=int(s[0])
    s=s[1]
    s=s.split(",")
    ideb, ifin = int(s[0]), int(s[1])
    return ADstatus, ideb, ifin

def readHeader(data):

    # lecture entete fichier norme IEEE488.2
    # #xyyyyyyy
    s=struct.unpack_from('2c',data)
    sizeHeader=int(s[1])
    print sizeHeader
##    # lecture taille du bloc de data suivant
##    fmt=str(sizeHeader)+"c"
##
##    s=struct.unpack_from(fmt,data[2:])
##    L=len(s)
##    sizeBuffer=0
##    for i in range(L):
##        sizeBuffer = pow(10,i)*int(s[L-i-1]) + sizeBuffer
##    #lecture des 5 champ de 4 byte qui contituent le header
##    fmt=">5l"
##
##    header=struct.unpack_from(fmt,data[8:])
##    header = np.array(header)
##    header=sc.reshape(header,(1,5))
##    """
##     header(0) = index of first scan record in this block
##     header(1) = Number of scan records in this block
##     header(2) = Number of samples per enabled channel or scan record
##     header(3) = Time stamp of the first scan record in the block, in second
##     header(4) =  Time stamp of the first scan record in the block, in second
##    """
##    bufsize = sizeBuffer - 28 # 2+6+5*4
##    fmt=">"+str(bufsize/4)+"I"
##    buf=struct.unpack_from(fmt,data[28:])
##    buf=np.array(buf)
##    taille=bufsize/4
##    buf=buf[1::4]
    ##    print "taille buf = ",buf.shape
    sizeBuffer,header,buf=0,0,[]
    return sizeHeader,sizeBuffer,header,buf

DEV1 = "TCPIP::169.254.241.13::INSTR";
DEV2 ='TCPIP::169.254.241.19::INSTR';

#-------------------------------------------------------------------------------
# reccupere le handle des boitiers
#-------------------------------------------------------------------------------
h1 = getHandle(DEV1)
h2 = getHandle(DEV2)

#-------------------------------------------------------------------------------
# lecture du nom des boitires, identification
#-------------------------------------------------------------------------------
s1=getID(h1)
s2=getID(h2)
print s1,' / ',s2



#-------------------------------------------------------------------------------
# reset des modules
#-------------------------------------------------------------------------------
print "Reset des modules..."
err1 = doRST(h1)
err2 = doRST(h2)
h1.write("AD:STATUS:SCAN?")
print h1.read()
h1.write("AD:STATUS?")
print h1.read()


#-------------------------------------------------------------------------------
# Enable AD for all channel
#-------------------------------------------------------------------------------
err = h1.write(":AD:ENAB OFF;:AD:BUFF:SIZe?")
print "taille buffer acquisition = ", h1.read()
print "Activation des  modules AD..."
err1 = setAdEnableAll(h1)
err2 = setAdEnableAll(h2)

#-------------------------------------------------------------------------------
# couplage AC/DC pour tous les modules
#-------------------------------------------------------------------------------
print "Couplage  des  voies en AC ..."
err1 = setCouplage(h1,'AC')
err2 = setCouplage(h2,'AC')

#-------------------------------------------------------------------------------
# mode acquisition du buffer wrap/no wrap
#-------------------------------------------------------------------------------
print "Mode acquisition buffer wrap/no wrap ..."
err1 = setWrap(h1,"on")  #   buffer circulaire
err1 = setWrap(h2,"on")

#-------------------------------------------------------------------------------
# initialisation des gains pour toutes les voies  1/10
#-------------------------------------------------------------------------------
print "Initialisation des gains ..."
level=1   # 1V en entree
err1 = setGain(h1,level)
err2 = setGain(h2,level)

#-------------------------------------------------------------------------------
# horloge interne
#-------------------------------------------------------------------------------
print "Initialisation horloge interne ..."
err1=setADClockInternal(h1)
err2=setADClockInternal(h2)

#-------------------------------------------------------------------------------
# frequence horloge interne
#-------------------------------------------------------------------------------
print "Initialisation frequence horloge interne ..."
fs=50000   # 10000 Hz
err1=setFreqClock(h1,fs)
err2=setFreqClock(h2,fs)
dt=1.0/fs    #periode echantillonnange
#-------------------------------------------------------------------------------
# trigger immediat / software
#-------------------------------------------------------------------------------
print "Initialisation trigger source immediat ..."
err1=setAdTrigSourceImm(h1)
#err2=setAdTrigSourceImm(h2)

#-------------------------------------------------------------------------------
# pret a lancer la mesure
#-------------------------------------------------------------------------------
print "Armement des mesures, pret a lancer ..."
err1=setAdArm(h1)
#err2=setAdArm(h2)

#-------------------------------------------------------------------------------
# lance la mesure la mesure
#-------------------------------------------------------------------------------
print "lance la mesure ...."
err1=setAdInit(h1)
#err2=setAdInit(h2)
buf=[]

sizeblock=254
iprec=-1
etat=0
for loop in range(10):
    ADstatus, ideb, ifin=GetAdBufferStatus(h1)
    ideb = ideb % 524032
    ifin = ifin % 524032
##    print "status=",ADstatus," ",bin(ADstatus),"err1=",err1," ideb=",ideb," ifin=",ifin
    if ideb==1:
        iprec,i=iprec+1,ifin
        print "lire de :",iprec," a ",i

        iprec=ifin

    if (ideb>1 and etat==0):
        iprec,i=iprec+1,524031
        print "lire de :",iprec," a ",i
        iprec=-1
        etat=1

    if (ideb>1 and etat==1):
        iprec,i=iprec+1,ideb
        if i>iprec:
            print "lire de :",iprec," a ",i
            iprec=ideb
        else:
            iprec,i=iprec+1,524031
            print "lire de :",iprec," a ",i
            iprec=-1
    time.sleep(0.05)


exit(0)
##    print isRunning

tacq=30 # temps acquisition 1s
##print "attente ..."
buffersize=tacq/dt # nombre d echantillon pour tacq
##print "nb. element : ", buffersize

N=200 #254  # work well only with 100 !!!!!!!!!!!!!!!!! or less than 255 (254)


nbblock=int(buffersize/N-1)
##print "nb. de blocs : ",nbblock
time.sleep(tacq)  #attente 2s

#-------------------------------------------------------------------------------
# arrete la mesure la mesure
#-------------------------------------------------------------------------------
err1=setAdStop(h1)
#err2=setAdStop(h2)


#-------------------------------------------------------------------------------
# on reccupere les donnees
#-------------------------------------------------------------------------------
t0= time.clock()

mess=":AD:FETCH? 0,"+str(N-1)+"\n"
##print "---------------------------"
##print mess
err1=h1.write (mess)
data=h1.read_raw()



sizeHeader,sizeBuffer,header,buf =  readHeader(data)
##print sizeHeader,sizeBuffer
##print header

for i in range(1,nbblock):
##    print "---------------------------"
    mess=":AD:FETCH? "+str(i*N) +","+str(N)+"\n"
##    print mess
    err1=h1.write (mess)
##    print "retour fetch = ",err1
    data1=h1.read_raw()
    sizeHeader,sizeBuffer,header,buf1 =  readHeader(data1)
##    print sizeHeader,sizeBuffer
##    print header
    #
    buf=np.concatenate(( buf,buf1), axis=0)

t= time.clock() - t0 # t is wall seconds elapsed (floating point)
print "duree = ",t

print "arret de la mesure ...."
plt.figure(1)
plt.plot(buf)
##fic = open("sinus.dat","wb")
##fic.write(data)
##fic.close()
plt.show()
exit(0)






